<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<h1>
	<fmt:message key="rewards.create.title" />
</h1>

<div id="message" class="alert alert-info">
	The reward has been created.
</div>

<div id="error" class="alert alert-danger">
	This should be hidden, so your JavaScript has a syntax error.
</div>

<spring:url value="/rewards" var="rewardUrl" />
<form:form modelAttribute="dining" action="${rewardUrl}" method="post" role="form" class="form-horizontal">
	<fieldset>
		<legend>
			<fmt:message key="rewards.create.legend"/>
		</legend>
		<div class="form-group">
			<label class="control-label col-sm-2" for="creditCardNumber">
				<fmt:message key="label.Reward.credit.card.number" />
			</label>
			<div class="col-sm-4">
				<form:input path="creditCardNumber" class="form-control" />
			</div>
			<div class="col-sm-6">
			</div>
		</div>
		<div class="form-group">
			<label class="control-label col-sm-2" for="amount">
				<fmt:message key="label.Reward.amount" />
			</label>
			<div class="col-sm-4">
				<form:input path="amount" class="form-control"/>
			</div>
			<div class="col-sm-6">
				<form:errors cssClass="alert alert-danger" path="amount" />
			</div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<button id="saveButton" type="submit" class="btn button-default">
					<fmt:message key="command.save" />
				</button>
			</div>
		</div>
	</fieldset>
</form:form>

<script type="text/javascript">
	var stompClient = null;

	/**
	 * On page load hide message and error divs, enhance saveButton to invoke
	 * processAjaxSubmit() when clicked
	 */
	$(function() {
		$("#message").hide();
		$("#error").hide();
		$("#saveButton").on('click', processAjaxSubmit);
		connect();
	});

	/**
	 * When save button is clicked: validate form then submit via an AJAX POST.
     * If the the POST is successful, send a message to /app/rewards
	 */
	function processAjaxSubmit(event) {
		var creditCardNumber = $("#creditCardNumber").val();
		var amount = $("#amount").val();

		if (creditCardNumber.length == 0) {
			$("#creditCardNumber").focus(); // Force focus to missing field
		} else if (amount.length == 0) {
			$("#amount").focus(); // Force focus to missing field
		} else {
			var rewardURL = "${rewardUrl}";

			// Setup request object
			var params = {
				creditCardNumber : creditCardNumber,
				amount : amount
			}

			// Submit new reward via na AJAX POST 
			$.post(rewardURL, params, function(data, textStatus, jqXhr) {
				stompClient.send('/app/rewards', {}, creditCardNumber);
				$("#error").hide();
				$("#message").fadeIn('fast');
			}).fail(function(data) {
				console.log("failed")
				$("#message").hide();
				$("#error").html("An error occurred on the server. Please specify a valid credit card number" +
					" (such as 1234123412341234) and a non-zero amount.");
				$("#error").fadeIn('fast');
			});
		}
		return false;
	}

	/**
	 * Log successful connection of STOMP client and subscribe to /topic/rewards
	 * Defines a callback to log any message received from /topic/rewards
	 */
	function subscribeUsingLoggingCallback(frame) {
		console.log('Connected: ' + frame);

		stompClient.subscribe('/topic/rewards', function(msg) {
			console.log('message received: ' + msg.body);
		});
	}

	/**
	 * Setup STOMP client.
	 */
	function connect() {
		var socket = new SockJS('${rewardUrl}');
		stompClient = Stomp.over(socket);
		
		// Connect and invoke subscribeJUsingLoggingCallback() if successful
		stompClient.connect({}, subscribeUsingLoggingCallback);
	}
</script>